$(function () {
    var options = {
        toolbar: "#qtpzcontent_toolbar",
        fitColumns: true,
        fit: true,
        singleSelect: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        rownumbers: true,
        showFooter: true,
        autoRowHeight: true,
        nowrap: false,
        columns: [
            [
                {field: 'checked', checkbox: true, title: "选择"},
                {field: 'zy', title: '摘要', width: 50, editor: {type: 'text', options: {required: true}}},
                {field: 'kmmc', title: '科目', width: 50, editor: {type: 'text', options: {required: true}}},
                {field: 'jfje', title: '借方', width: 30, formatter: function (value) {
                    var sl = formatJe(value, ",");
                    return sl;
                }, editor: {type: 'numberbox', options: {groupSeparator: ',', precision: 2, fit: true}}},
                {field: 'dfje', title: '贷方', width: 30, formatter: function (value) {
                    var sl = formatJe(value, ",");
                    return sl;
                }, editor: {type: 'numberbox', options: {groupSeparator: ',', precision: 2, fit: true}}},
                {field: 'fzhs', title: '辅助核算', width: 50, align: 'center', formatter: formatColumn}
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            datagridOnSelectHandle(rowIndex, rowData);
            $("a[name='edit']").linkbutton({
                plain: true,
                iconCls: 'icon-edit'
            });
            $("a[name='tip']").tips();
        },
        onLoadSuccess: function () {
            $("a[name='edit']").linkbutton({
                plain: true,
                iconCls: 'icon-edit'
            });
            //$("a[name='tip']").tips();
        }
    };

    var data = {
        rows: [
            {
                "id": "",
                "zy": "",
                "kmdm": "",
                "kmmc": "",
                "jfje": "",
                "dfje": "",
                "fzhs": ""
            },
            {
                "id": "",
                "zy": "",
                "kmdm": "",
                "kmmc": "",
                "jfje": "",
                "dfje": "",
                "fzhs": ""
            }
        ],
        footer: [
            {"zy": "合计", "jfje": "", "dfje": ""}
        ]
    };

    var qtpzId = $("#qtpzcontent_toolbar [name='qtpz.id']").val();

    if (qtpzId == "") {
        $.extend(options, {data: data});
    } else {
        $.extend(options, {url: $.webPath() + '/cwgl/qtpz/findQtpzfl', queryParams: {id: qtpzId}});
    }

    var grid = $('#qtpzcontent_edatagrid').edatagrid(options);
    //新增分录
    $("#qtpzcontent_toolbar [name='xzfl']").click(function () {
        $(grid).edatagrid('appendRow', {
            "id": "",
            "zy": "",
            "kmdm": "",
            "kmmc": "",
            "jfje": "",
            "dfje": "",
            "fzhs": ""
        });
        $(grid).edatagrid('resize');
    });
    //删除分录
    $("#qtpzcontent_toolbar [name='scfl']").click(function () {
        var rows = $(grid).edatagrid("getChecked");
        if (rows.length == 0) {
            $.messager.alert("提示", "请先勾选凭证分录!");
            return;
        }
        if (rows) {
            $.messager.confirm('提示', '是否确定删除该分录?', function (r) {
                if (r) {
                    $.each(rows, function (i, val) {
                        var index = $(grid).edatagrid('getRowIndex', val);
                        $(grid).edatagrid('deleteRow', index);
                    });
                }
            });
        }
        $(grid).edatagrid('resize');
    });

    function datagridOnSelectHandle(rowIndex, rowData) {
        $(grid).edatagrid('editRow', rowIndex);
        var editors = $(grid).datagrid('getEditors', rowIndex);
        if (editors.length == 0)
            return;
        //科目
        editors[1].target.unbind("dblclick").bind('dblclick', function () {
            var gsId = $("#qtpzcontent_toolbar [name='qtpz.nbgs.id']").val();
            if (gsId == "") {
                $.messager.alert("提示", "请选择公司！");
                return;
            }
            searchsubjectcodewindow(openSearchWindowOKbtnHandle, this, gsId);
        });
        //借方
        editors[2].target.unbind("change").bind("change", function () {
            var temp = parseFloat($(this).val()).toFixed(2);
            countSum(temp, "jfje", rowIndex);
        });
        editors[2].target.unbind("keyup").bind("keyup", function () {
            var row = $(grid).datagrid('getSelected');
            row["dfje"] = "";
            editors[3].target.val("");
            $(editors[3].target).next().val("");
            countSum(0, "dfje", rowIndex);
        });
        //贷方
        editors[3].target.unbind("change").bind("change", function () {
            var temp = parseFloat($(this).val()).toFixed(2);
            countSum(temp, "dfje", rowIndex);
        });
        editors[3].target.unbind("keyup").bind("keyup", function () {
            var row = $(grid).datagrid('getSelected');
            row["jfje"] = "";
            editors[2].target.val("");
            $(editors[2].target).next().val("");
            countSum(0, "jfje", rowIndex);
        });
    }


    function openSearchWindowOKbtnHandle(data, input) {
        var row = $(grid).edatagrid("getSelected");
        var index = $(grid).edatagrid("getRowIndex", row);
        row["kmdm"] = data.code;
        row["kmmc"] = data.code + "__" + data.pathname;
        row["fzhs"] = data.fzhslx;
        $(input).val(data.code + "__" + data.pathname);
        $(grid).edatagrid("acceptChanges");
        $(grid).edatagrid("selectRow", index);
        if (data.fzhslx)
            fzhsDialog(data.fzhslx, index);
    }

    //计算合计金额
    function countSum(temp, type, rowIndex) {
        var jfSum = 0;
        var dfSum = 0;
        var data = $(grid).edatagrid("getData");
        for (var i = 0; i < data.rows.length; i++) {
            //借方合计
            var jfTemp = 0;
            if (type == "jfje" && i == rowIndex)
                jfTemp = isNaN(temp) ? 0 : parseFloat(temp);
            else
                jfTemp = parseFloat(data.rows[i]['jfje']);
            jfTemp = isNaN(jfTemp) ? 0 : parseFloat(jfTemp);
            jfSum += jfTemp;
            //贷方合计
            var dfTemp = 0;
            if (type == "dfje" && i == rowIndex)
                dfTemp = isNaN(temp) ? 0 : parseFloat(temp);
            else
                dfTemp = parseFloat(data.rows[i]['dfje']);
            dfTemp = isNaN(dfTemp) ? 0 : parseFloat(dfTemp);
            dfSum += dfTemp;
        }
        var footer = $(grid).edatagrid("getFooterRows");
        if (type == "jfje")
            footer[0]["jfje"] = parseFloat(jfSum).toFixed(2);
        if (type == "dfje")
            footer[0]["dfje"] = parseFloat(dfSum).toFixed(2);
        $(grid).datagrid('reloadFooter', footer);
    }

    function formatColumn(value, row, index) {
        if (typeof(value) == "undefined" || value.length == 0)
            return "";
        var items = [];
//        if ($.trim(value) != "")
//            items = value.split("；");
        items = new Array();
        var regexpArray = [/客户/, /供应商/, /部门/, /个人/, /项目/];
        var regexpText = ["客户", "供应商", "部门", "职员", "项目核算"];
        for (var r = 0; r < regexpArray.length; r++) {
            if (value.search(regexpArray[r]) != -1)
                items.push(regexpText[r]);
        }
        var temp = "";
        if (items.length != 0) {
            for (var i = 0; i < items.length; i++) {
                if (row["fzhsList[" + i + "].code"] == "" || row["fzhsList[" + i + "].code"] == undefined) {
                    temp += "";
                } else if (row["fzhsList[" + i + "].name"] == "" || row["fzhsList[" + i + "].name"] == undefined || row["fzhsList[" + i + "].name"] == "null") {
                    temp += "<p>" + items[i] + ":" + row["fzhsList[" + i + "].code"] + "</p>";
                } else {
                    temp += "<p>" + items[i] + ":" + row["fzhsList[" + i + "].code"] + "_" + row["fzhsList[" + i + "].name"] + "</p>";
                }
//                temp += row["fzhsList[" + i + "].code"] == "" || row["fzhsList[" + i + "].code"] == undefined ||  row["fzhsList[" + i + "].name"] ==""
//                    ? "" : items[i] + ":" + row["fzhsList[" + i + "].code"] + "_" + row["fzhsList[" + i + "].name"];
            }
            return temp + '<a name="edit" href="javascript:void(0)"  onclick="fzhsDialog(\'' + value + '\',' + index + ')"></a>';
        } else
            return "";
    }
});

function fzhsDialog(value, index) {
    var gsId = $("#qtpzcontent_toolbar [name='qtpz.nbgs.id']").val();
    if (gsId == "") {
        $.messager.alert("提示", "请选择公司！");
        return;
    }
    var items = null;
    var win = $.window({
        title: "辅助核算项",
        iconCls: "icon-add",
        width: 300,
        height: 230,
        cache: false,
        modal: true,
        contents: '<div class="textcon"><table id="fzhs_window" style="width:100%" class="tb"><col width="20%"/><col width="80%"/></table></div>',
        onComplete: function () {
            //items = $.trim(value).split("；");
            items = new Array();
            var regexpArray = [/客户/, /供应商/, /部门/, /个人/, /项目/];
            var regexpText = ["客户", "供应商", "部门", "职员", "项目核算"];
            for (var r = 0; r < regexpArray.length; r++) {
                if (value.search(regexpArray[r]) != -1)
                    items.push(regexpText[r]);
            }
            var itemsArray = new Array();
            for (var i = 0; i < items.length; i++) {
                switch (items[i]) {
                    case "客户":
                        itemsArray.push("<tr><td>客户</td><td><input id='customercode' type='text' class='input-text'/></td></tr>");
                        break;
                    case "供应商":
                        itemsArray.push("<tr><td>供应商</td><td><input id='suppliercode' type='text' class='input-text'/></td></tr>");
                        break;
                    case "部门":
                        itemsArray.push("<tr><td>部门</td><td><input id='departmentcode' type='text' class='input-text'/></td></tr>");
                        break;
                    case "职员":
                        itemsArray.push("<tr><td>职员</td><td><input id='staffcode' type='text' class='input-text'/></td></tr>");
                        break;
                    case "数量":
                        itemsArray.push("<tr><td>数量</td><td><input id='qty' type='text' class='input-text'/></td></tr>");
                        break;
                    default :
                        //itemsArray.push("<tr><td>" + items[i] + "</td><td><input id='" + _tyfzhsmc[items[i]] + "' type='text' class='input-text'/></td></tr>");
                        itemsArray.push("<tr><td>" + items[i] + "</td><td><input id='_qtpz_xmhs' type='text' class='input-text'/></td></tr>");
                }
            }
            $(this).find("#fzhs_window").append(itemsArray.join(""));
            var row = $('#qtpzcontent_edatagrid').datagrid("getData");
            row = row["rows"][index];
            for (var i = 0; i < items.length; i++) {
                switch (items[i]) {
                    case "客户":
                        $(this).find("#customercode").combobox({
                            valueField: 'kmdm',
                            textField: 'qyqc',
                            required: true,
                            filter: function (q, row) {
                                var opts = $(this).combobox('options');
                                return row[opts.textField].indexOf(q) >= 0;
                            },
                            url: $.webPath() + '/cwgl/kmys/ljkmdmys/findKmdm?nbgsId=' + gsId + "&type=1",
                            formatter: function (row) {
                                var opts = $(this).combobox('options');
                                var kv = row[opts.valueField];
                                var array = kv.split("@");
                                return array[0] + "   " + row[opts.textField];
                            }
                        });
                        $(this).find("#customercode").combobox("setValue", row["fzhsList[" + i + "].code"]);
                        break;
                    case "供应商":
                        $(this).find("#suppliercode").combobox({
                            valueField: 'kmdm',
                            textField: 'qyqc',
                            required: true,
                            filter: function (q, row) {
                                var opts = $(this).combobox('options');
                                return row[opts.textField].indexOf(q) >= 0;
                            },
                            url: $.webPath() + '/cwgl/kmys/ljkmdmys/findKmdm?nbgsId=' + gsId + "&type=0",
                            formatter: function (row) {
                                var opts = $(this).combobox('options');
                                var kv = row[opts.valueField];
                                var array = kv.split("@");
                                return array[0] + "   " + row[opts.textField];
                            }
                        });
                        $(this).find("#suppliercode").combobox("setValue", row["fzhsList[" + i + "].code"]);
                        break;
                    case "部门":
                        $(this).find("#departmentcode").combobox({
                            valueField: 'kmdm',
                            textField: 'bmqc',
                            required: true,
                            filter: function (q, row) {
                                var opts = $(this).combobox('options');
                                return row[opts.textField].indexOf(q) >= 0;
                            },
                            url: $.webPath() + '/organ/gsjg/findKmdm?gsjgId=' + gsId,
                            formatter: function (row) {
                                var opts = $(this).combobox('options');
                                return row[opts.valueField] + "   " + row[opts.textField];
                            }
                        });
                        $(this).find("#departmentcode").combobox("setValue", row["fzhsList[" + i + "].code"]);
                        break;
                    case "职员":
                        $(this).find("#staffcode").combobox({
                            valueField: 'kmdm',
                            textField: 'xm',
                            required: true,
                            filter: function (q, row) {
                                var opts = $(this).combobox('options');
                                return row[opts.textField].indexOf(q) >= 0;
                            },
                            url: $.webPath() + '/sys/yg/findKmdm?zggsId=' + gsId,
                            formatter: function (row) {
                                var opts = $(this).combobox('options');
                                return row[opts.valueField] + "   " + row[opts.textField];
                            }
                        });
                        $(this).find("#staffcode").combobox("setValue", row["fzhsList[" + i + "].code"]);
                        break;
                    case "数量":
                        $(this).find("#qty").numberbox({
                            required: true,
                            min: 0,
                            precision: 4
                        });
                        $(this).find("#qty").numberbox("setValue", row["fzhsList[" + i + "].code"]);
                        break;
                    default :
//                        $(this).find("#" + _tyfzhsmc[items[i]]).combotree({
//                            required: true,
//                            url: $.webPath() + '/cwgl/kmys/tyfzhsys/get_tyfzhsystreejson?tyfzhsmcId=' + _tyfzhsmcId[items[i]] + "&flag=false",
//                            _id: _tyfzhsmc[items[i]],
//                            onBeforeSelect: function (node) {
//                                var opts = $(this).tree('options');
//                                var t = $("#" + opts._id).combotree('tree');
//                                var isLeaf = t.tree("isLeaf", node.target);
//                                if (!isLeaf)
//                                    $.messager.alert("提示", "请选择末级辅助核算!", "warning");
//                                return isLeaf;
//                            }
//                        });
//                        $(this).find("#" + _tyfzhsmc[items[i]]).combotree("setValue", row["fzhsList[" + i + "].code"]);
                        $(this).find("#_qtpz_xmhs").combotree({
                            required: true,
                            url: $.webPath() + '/cwgl/kmys/tyfzhsys/get_tyfzhsystreejson?tyfzhsmcId=-1&flag=false',
                            onBeforeSelect: function (node) {
                                var opts = $(this).tree('options');
                                var t = $("#_qtpz_xmhs").combotree('tree');
                                var isLeaf = t.tree("isLeaf", node.target);
                                if (!isLeaf)
                                    $.messager.alert("提示", "请选择末级辅助核算!", "warning");
                                return isLeaf;
                            }
                        });
                        $(this).find("#_qtpz_xmhs").combotree("setValue", row["fzhsList[" + i + "].code"]);
                }
            }
        },
        buttons: [
            {
                text: '确定',
                handler: function () {
                    var valid = true;
                    var row = $('#qtpzcontent_edatagrid').datagrid("getSelected");
                    for (var i = 0; i < items.length; i++) {
                        switch (items[i]) {
                            case "客户":
                                valid = valid && $(win).find("#customercode").combobox("isValid");
                                //row["fzhsList[" + i + "].type"] = "customercode";
                                row["fzhsList[" + i + "].type"] = "cust_id";
                                var kv = $(win).find("#customercode").combobox("getValue");
                                var array = kv.split("@");
                                row["fzhsList[" + i + "].code"] = array[0];
                                row["fzhsList[" + i + "].name"] = $(win).find("#customercode").combobox("getText");
                                row["fzhsList[" + i + "].gsId"] = array[2];
                                row["fzhsList[" + i + "].gstype"] = array[3];
                                break;
                            case "供应商":
                                valid = valid && $(win).find("#suppliercode").combobox("isValid");
                                //row["fzhsList[" + i + "].type"] = "suppliercode";
                                row["fzhsList[" + i + "].type"] = "supplier_id";
                                var kv = $(win).find("#suppliercode").combobox("getValue");
                                var array = kv.split("@");
                                row["fzhsList[" + i + "].code"] = array[0];
                                row["fzhsList[" + i + "].name"] = $(win).find("#suppliercode").combobox("getText");
                                row["fzhsList[" + i + "].gsId"] = array[2];
                                row["fzhsList[" + i + "].gstype"] = array[3];
                                break;
                            case "部门":
                                valid = valid && $(win).find("#departmentcode").combobox("isValid");
                                //row["fzhsList[" + i + "].type"] = "departmentcode";
                                row["fzhsList[" + i + "].type"] = "dept_id";
                                row["fzhsList[" + i + "].code"] = $(win).find("#departmentcode").combobox("getValue");
                                row["fzhsList[" + i + "].name"] = $(win).find("#departmentcode").combobox("getText");
                                break;
                            case "职员":
                                valid = valid && $(win).find("#staffcode").combobox("isValid");
                                //row["fzhsList[" + i + "].type"] = "staffcode";
                                row["fzhsList[" + i + "].type"] = "personnel_id";
                                row["fzhsList[" + i + "].code"] = $(win).find("#staffcode").combobox("getValue");
                                row["fzhsList[" + i + "].name"] = $(win).find("#staffcode").combobox("getText");
                                break;
                            case "数量":
                                valid = valid && $(win).find("#qty").numberbox("isValid");
                                row["fzhsList[" + i + "].type"] = "qty";
                                row["fzhsList[" + i + "].code"] = $(win).find("#qty").numberbox("getValue");
                                row["fzhsList[" + i + "].name"] = "";
                                break;

                            default:
//                                valid = valid && $(win).find("#" + _tyfzhsmc[items[i]]).combobox("isValid");
//                                row["fzhsList[" + i + "].type"] = _tyfzhsmc[items[i]];
//                                row["fzhsList[" + i + "].code"] = $(win).find("#" + _tyfzhsmc[items[i]]).combobox("getValue");
//                                row["fzhsList[" + i + "].name"] = $(win).find("#" + _tyfzhsmc[items[i]]).combobox("getText");
                                valid = valid && $(win).find("#_qtpz_xmhs").combobox("isValid");
                                var t = $(win).find("#_qtpz_xmhs").combotree('tree');
                                var node = t.tree('getSelected');
                                alert(node.attributes);
                                row["fzhsList[" + i + "].type"] = node.attributes;
                                row["fzhsList[" + i + "].code"] = $(win).find("#_qtpz_xmhs").combobox("getValue");
                                row["fzhsList[" + i + "].name"] = $(win).find("#_qtpz_xmhs").combobox("getText");
                        }
                    }
                    if (valid) {
                        $('#qtpzcontent_edatagrid').edatagrid("acceptChanges");
                        $(win).window("close");
                    }
                }
            }
        ]
    })
}


